<?php
/**
 * 登录
 */

namespace Api;

use Config\mysql;
use http\Exception;
use Logic\KeyHandle;
use Logic\PraiseLogic;
use Logic\RateLimit;
use Logic\RedisClientLogic;
use Logic\WishesLogic;

header('Content-Type:application/json; charset=utf-8');

class IndexController extends CommonController
{

    /**
     * 获取我的点赞数
     */
    public function getMyPraiseNum()
    {
        $token = $_GET['token'];
        if (empty($token) || mb_strlen($token) > 64) {
            $this->returnJson(-1, 'token非法!', []);
        }
        $user = $this->validateUser($token);
        if (empty($user)) {
            $this->returnJson(-1, '非法用户!', []);
        }

        $wishId = $user['my_wish_id'];
        $isLingQu = $user['is_reveive_cdk'];
        $cdk = $user['cdk'];
        $reveiveNum = PraiseLogic::getUserReveivePraiseNum($wishId);
        $dzNum = PraiseLogic::getUserProvideDianZanNum($user['uid']);
        $this->returnJson(
            0,
            '获取成功!',
            [
                'reveiveNum' => (int)$reveiveNum,
                'dzNum' => (int)$dzNum,
                'isLingQu' => (int)$isLingQu,
                'CDK' => $cdk
            ]
        );
    }

    /**
     * 随机展示10条祝福语
     */
    public function showWishs()
    {
        $token = $_GET['token'];
        if (empty($token) || mb_strlen($token) > 64) {
            $this->returnJson(-1, 'token非法!', []);
        }
        $user = $this->validateUser($token);
        if (empty($user)) {
            $this->returnJson(-1, '非法用户!', []);
        }

        //限流
        $limit = new RateLimit();
        $limit->minLimit($user['uid']);

        $redis = RedisClientLogic::getInstance();
        $randWishes = $redis->sRandMember(RANDOM_WISHES, 10);
        $randWishesList = [];
        if ($randWishes) {
            $randWishesList = WishesLogic::getWishesList($randWishes);
        }
        $this->returnJson(0, '获取成功!', $randWishesList);
    }

    /**
     * 发送祝福语
     */
    public function sendWishs()
    {
        //判断该用户是否发送过祝福语
        $token = $_POST['token'];
        if (empty($token) || mb_strlen($token) > 64) {
            $this->returnJson(-1, 'token非法!', []);
        }
        $user = $this->validateUser($token);
        if (empty($user)) {
            $this->returnJson(-1, '非法用户!', []);
        }
        //限流
        $limit = new RateLimit();
        $limit->minLimit($user['uid']);

        $redis = RedisClientLogic::getInstance();
        if ($redis->hGet(USER_WISHES, $user['uid'])) {
            $this->returnJson(-1, '您已发送过祝福语，活动期间只能发一条哦!', []);
        }
        $content = htmlspecialchars($_POST['content']);
        if (mb_strlen($content) > 100) {
            $this->returnJson(-1, '祝福语过长!', []);
        }
        if (empty($content)) {
            $this->returnJson(-1, '祝福语内容不能为空!', []);
        }
        $wishs = new WishesLogic();
        //祝福语入库
        $res = $wishs->saveWishes($user['uid'], $content);
        if ($res['res'] == 0) {
            //处理redis
            $dealRes = KeyHandle::dealKey($user['uid'], $res['wish_id'], $token);
            if (isset($dealRes['res']) && $dealRes['res'] != 0) {
                $this->returnJson(0, '发送异常请稍后重试!', []);
            }
            $this->returnJson(0, '发送成功!', []);
        }
        //如果入库失败，检查mysql与redis key的一致性
        KeyHandle::findKeyExists($user['uid'], $token);
        $this->returnJson(-1, $res['msg'] ?? '失败', []);
    }

    /**
     * 点赞祝福语
     */
    public function givePraise()
    {
        $token = $_POST['token'];
        $wishId = $_POST['wish_id'] ?? '';
        if (empty($token) || mb_strlen($token) > 64) {
            $this->returnJson(-1, 'token非法!', []);
        }
        $user = $this->validateUser($token);
        if (empty($user)) {
            $this->returnJson(-1, '非法用户!', []);
        }
        //限流
        $limit = new RateLimit();
        $limit->minLimit($user['uid']);

        $redis = RedisClientLogic::getInstance();
        //判断该祝福语是否存在
        $existWish = $redis->sIsMember(RANDOM_WISHES, $wishId);
        if ($existWish === false) {
            $this->returnJson(0, '该祝福语不存在!', []);
        }
        //判断该祝福语是否被该用户进行过点赞
        $thisPraiseKey = PER_WISHTID_RECEIVE_PRAISE_LIST . ":" . $wishId;
        $give_prise_uid = $redis->sIsMember($thisPraiseKey, $user['uid']);
        if ($give_prise_uid) {
            $this->returnJson(0, '您已经点赞了这条祝福语，不能重复点赞哦!', []);
        }
        $todayNumKey = TODAY_MY_DIANZAN . ':' . date('Y-m-d');
        $todayGivePrizeNum = $redis->hGet($todayNumKey, $user['uid']);
        if (($todayGivePrizeNum <=> PER_DAY_LIMIT_GIVE_PRIZE) === 0) {
            $this->returnJson(0, '您今日点赞已达上限，不能再点赞了哦!', []);
        }
        $res = PraiseLogic::givePrize($user, $wishId, $thisPraiseKey);
        $this->returnJson($res['res'] ?? 0, $res['msg'] ?? '', $res['data'] ?? []);
    }

    /**
     * 祝福语排行榜
     */
    public function wishesRanking()
    {
        $token = $_GET['token'];
        if (empty($token) || mb_strlen($token) > 64) {
            $this->returnJson(-1, 'token非法!', []);
        }
        $user = $this->validateUser($token);
        if (empty($user)) {
            $this->returnJson(-1, '非法用户!', []);
        }

        //限流
        $limit = new RateLimit();
        $limit->minLimit($user['uid']);

        $page = $_GET['page'] ?? 1; //页码
        $pageSize = $_GET['page_size'] ?? 10;
        $redis = RedisClientLogic::getInstance();
        $total = $redis->zCard(ORDER_WISHES); //总条数
        $totalPageNum = 0;
        $listArr = [];
        if ($total > 0) {
            $totalPageNum = ceil(($total + $page - 1) / $pageSize);
            $start = $pageSize * ($page - 1);
            $end = $start + ($pageSize - 1);
            $listId = $redis->zRevRange(ORDER_WISHES, $start, $end);
            //mysql查询祝福语详情
            if ($listId) {
                $dataList = WishesLogic::getWishesList($listId);
                for ($i = 0; $i < count($listId); $i++) {
                    foreach ($dataList as $key => $v) {
                        if ($v['id'] == $listId[$i]) {
                            array_push($listArr, $v);
                        }
                    }
                }
            }
        }
        $data = [
            'list' => $listArr,
            'page' => [
                'total_page' => $totalPageNum ?? 0,
                'total_num' => $total ?? 0
            ],
        ];
        $this->returnJson(0, '获取成功!', $data);
    }


    /**
     * 获取登录用户收到的点赞者昵称、头像列表
     */
    public function getMyselfPraise()
    {
        $token = $_GET['token'];
        $page = $_GET['page'] ?? 1; //页码
        $scan = $_GET['scan'] ?? 2; //迭代
        $pageSize = $_GET['page_size'] ?? 10;
        if (empty($token) || mb_strlen($token) > 64) {
            $this->returnJson(-1, 'token非法!', []);
        }
        $user = $this->validateUser($token);
        if (empty($user)) {
            $this->returnJson(-1, '非法用户!', []);
        }
        $redis = RedisClientLogic::getInstance();
        //获取该用户的发送的祝福语id
        $wishId = $user['my_wish_id'];
        //对该祝福语点赞的用户列表
        $thisPraiseKey = PER_WISHTID_RECEIVE_PRAISE_LIST . ":" . $wishId;
//        $givePriseUid = $redis->sMembers($thisPraiseKey);
        $iterator = null;
        $givePriseUid = $redis->sScan($thisPraiseKey, $iterator, null, 2);
//        $this->returnJson(-1, '获取成功!', $givePriseUid);
        $row = [];
        if ($givePriseUid) {
            $dbLink = mysql::mysql();
            $givePriseUid = implode(',', $givePriseUid);
            $st = $dbLink->prepare(
                'SELECT uid,nickname,avator FROM `tbUser` WHERE uid IN (' .$givePriseUid . ')'
            );
            $st->execute();
            $row = $st->fetchAll(\PDO::FETCH_ASSOC);
        }
        $this->returnJson(-1, '获取成功!', ['list' => $row, 'scan' => $scan]);
    }

    /**
     * 领取CDK
     */
    public function reveiveCDK()
    {
        $token = $_GET['token'];
        if (empty($token) || mb_strlen($token) > 64) {
            $this->returnJson(-1, 'token非法!', []);
        }
        $user = $this->validateUser($token);
        if (empty($user)) {
            $this->returnJson(-1, '非法用户!', []);
        }

        //限流
        $limit = new RateLimit();
        $limit->minLimit($user['uid']);
        $praise = new PraiseLogic();
        //是否完成任务
        $res = $praise->validateTask($user);
        if ($res === 0) {
            $this->returnJson(-1, '您还未完成任务，无法领取!', []);
        }
        //是否已经领取过CDK
        $res = $praise->validateCdk($user);
        if ($res === 1) {
            $this->returnJson(-1, '您已经领取过CDK，活动期间只能领取一次哦!', []);
        }
        //进行CDk领取
        $res = PraiseLogic::provideCdk($token, $user);
        $this->returnJson($res['res'] ?? 0, $res['msg'] ?? '', $res['data'] ?? []);
    }

}